<template>
  <el-dialog
    :title="title === 'add' ? '添加用户' : '更新用户'"
    :close-on-click-modal="false"
    :visible.sync="dialog"
    width="500px"
    @close="dialog = false"
  >
    <el-form
      label-position="center"
      label-width="100px"
      v-loading="ruleFormLoading"
      :model="user"
      :rules="rules"
      ref="user"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="登录名" prop="userName">
            <el-input
              placeholder="请输入登录名"
              v-model="user.userName"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="登录密码" prop="password">
            <el-input
              placeholder="请输入密码"
              v-model="user.password"
              type="password"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialog = false" size="mini">取 消</el-button>
      <el-button type="primary" @click="submit('user')" size="mini"
        >确 定</el-button
      >
    </div>
  </el-dialog>
</template>

<script>
import { addUser, updateUser } from "@/api/data";

export default {
  name: "addOrUpdateUser",
  data() {
    return {
      dialog: false,
      ruleFormLoading: false,
      title: "",
      user: {
        userName: "",
        password: "",
      },
      rules: {
        userName: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            message: "至少输入六位",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    initTableList() {
      this.$emit("initTableList");
    },
    submit(user) {
      this.$refs[user].validate((valid) => {
        this.ruleFormLoading = true;
        if (valid) {
          if (this.title === "edit") {
            updateUser(this.user).then((res) => {
              this.$message(res.data.msg);
              this.initTableList();
              this.dialog = false;
            });
          } else {
            this.user.remark = 1;
            addUser(this.user).then((res) => {
              this.$message(res.data.msg);
              this.initTableList();
              this.dialog = false;
            });
          }
          this.ruleFormLoading = false;
        } else {
          this.ruleFormLoading = false;
          return false;
        }
      });
    },
  },
};
</script>

<style scoped></style>
